package com.ruoyi.system.service.impl;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.core.domain.PushBody;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.push.JiGuangPushService;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.PushService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: ruohao
 * @Date: 2023/11/29
 **/
@Service
public class PushServiceImpl implements PushService {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    private JiGuangPushService service;

    @Resource
    private SysUserMapper sysUserMapper;

    /**
     * 推送
     * @param userId 用户id
     * @param content 推送内容
     * @param title 安卓专用 推送标题
     */
    @Override
    public void push(Long userId, String content, String title) {
        try {
            Long[] userIds = new Long[1];
            userIds[0] = userId;
            List<SysUser> sysUsers = sysUserMapper.selectUserByUserIds(userIds);
            if (CollectionUtils.isEmpty(sysUsers)) {
                return;
            }
            List<String> registerIds = sysUsers.stream().map(SysUser::getRegisterId).collect(Collectors.toList());
            if (CollectionUtils.isEmpty(registerIds)) {
                return;
            }
            PushBody pushBody = new PushBody();
            pushBody.setAlert(content);
            pushBody.setTitle(title);
            pushBody.setAlert(content);
            service.pushAndroid(pushBody, registerIds);
            service.pushIos(pushBody, registerIds);
        } catch (Exception e) {
            logger.error("推送失败 {} {} {}", userId, content, title);
        }
    }

    /**
     * 推送
     * @param userIds 用户ids
     * @param content 推送内容
     * @param title 安卓专用 推送标题
     */
    @Override
    public void push(List<Long> userIds, String content, String title) {
        try {
            List<SysUser> sysUsers = sysUserMapper.selectUserByUserIds(userIds.toArray(new Long[0]));
            if (CollectionUtils.isEmpty(sysUsers)) {
                return;
            }
            List<String> registerIds = sysUsers.stream().map(SysUser::getRegisterId).collect(Collectors.toList());
            if (CollectionUtils.isEmpty(registerIds)) {
                return;
            }
            PushBody pushBody = new PushBody();
            pushBody.setAlert(content);
            pushBody.setTitle(title);
            pushBody.setAlert(content);
            service.pushAndroid(pushBody, registerIds);
            service.pushIos(pushBody, registerIds);
        } catch (Exception e) {
            logger.error("推送失败 {} {} {}", JSON.toJSONString(userIds), content, title);
        }
    }
}
